<!--
//
// ChooseUserOne.vue
// hs-admin
//
// Created by 区区电脑 on 2023/09/26.
//
-->
<template>
    <div class="ChooseUserOne">
        <el-form-item :label="labels[0]" style="width: 50%">
            <el-tree-select v-model="state.orgIdV" :disabled="state.hasInsertData" clearable :check-strictly="true" :data="state.orgList" :default-expand-all="true" :props="{label: 'orgAllName', children: 'children'}" :render-after-expand="false" filterable style="width: 100%;" value-key="id" @change="onOrgChange" />
        </el-form-item>
        <el-form-item :label="labels[1]" style="width: 50%">
            <div style="display: flex;flex-direction: row;justify-content: flex-start;align-items: center">
                <el-select v-model="state.userIdV" :disabled="state.hasInsertData" filterable style="width: 100%" @change="onUserChange">
                    <el-option v-for="item in filterUserList" :key="item.id" :label="item.realName" :value="item.id" />
                </el-select>
                <el-input v-if="useTel" v-model="state.telV" :disabled="state.hasInsertData" placeholder="联系方式" @change="onTelChange">
                    <template #prepend>tel:</template>
                </el-input>
            </div>
        </el-form-item>
    </div>
</template>

<script setup>
import {ref, reactive, computed, onMounted, watch} from "vue";
import {useStore} from "vuex";
import {useRouter} from "vue-router";
import * as api from "./api.js"

const props = defineProps({
    orgId: {
        type: Number,
    },
    userId: {
        type: Number,
    },
    tel: {
        type: [String, Number],
        default: () => ""
    },
    labels: {
        type: Array,
        default: () => ["组织", "用户"]
    },
    bindOrg: {
        type: Boolean,
        default: () => true
    },
    filterUser: {
        type: Function,
    },
    useTel: {
        type: Boolean,
        default: () => true
    },
    org: {
        type: Object,
    },
    user: {
        type: Object,
    }
});
const emits = defineEmits(['update:orgId', 'update:userId', "update:tel", "orgChange", "userChange", "telChange"]);

// 路由
const router = useRouter();
// store
const store = useStore();

const _filterUserList = computed(() => {
    const list = state.userList.filter(user => user.orgIds.findIndex(orgId => orgId === state.orgIdV) > -1)
    // 这里为了处理筛选到的用户列表没有已绑定的用户id,这个时候下拉框会显示用户id，将关联的用户信息插入到没有筛选到的用户列表中（为了让下拉框在列表中筛选不到的情况下显示已绑定用户信息）
    const index = list.findIndex(user => user.id === props.userId)
    if (props.userId && index < 0 && props.user) {
        state.hasInsertData = true
        list.push(props.user)
    } else {
        state.hasInsertData = false
    }
    return list;
});
const filterUserList = computed(() => props.filterUser ? props.filterUser(_filterUserList.value) : _filterUserList.value)

const state = reactive({
    orgIdV: null,
    userIdV: null,
    telV: null,
    orgList: [],
    userList: [],
    hasInsertData: false
})

function onOrgChange(id) {
    if (props.bindOrg) {
        emits("update:orgId", id);
    }
    emits("orgChange", {})
    state.userIdV = null;
    state.telV = null;
    onUserChange(null)
}

function loadUserList() {
    api.GetUserList().then(({success, data}) => {
        if (!success) return 0;
        state.userList = data || [];
        // const index = state.userList.findIndex(user => user.id === props.userId)
        //
        // if (index < 0) {
        //     debugger
        //     state.userList.push(props.user);
        // }
    })
}

function onUserChange(id) {
    const user = state.userList.find(item => item.id === id);
    if (user) {
        emits("update:tel", user.phone)
    }
    emits("update:userId", id)
    emits("userChange", {}, user, user?.phone)
}

function onTelChange(v) {
    emits("update:tel", v)
    emits("telChange", v)

}

function setOrgId() {
    state.orgIdV = props.orgId
    setUserId()
}

function setUserId() {
    state.userIdV = props.userId
}

function setTel() {
    state.telV = props.tel
}

watch(() => props.orgId, () => {
    setOrgId()
})
watch(() => props.userId, () => {
    setUserId()
})
watch(() => props.tel, () => {
    setTel()
})

onMounted(() => {
    console.log("ChooseUserOne onMounted");
    setOrgId()
    setUserId()
    setTel()
    loadUserList()
    api.GetOrgTreeList().then(({success, data}) => {
        if (!success) return 0;
        const list = data || [];
        // 跟插入用户一样，为了处理在列表中筛选不到已绑定数据导致下拉框只显示 id 的情况，插入已绑定组织
        const org = list.treeFind(org => org.id === props.orgId)
        if (props.orgId && !org && props.org) {
            state.hasInsertData = true
            props.org.orgAllName = props.org.orgAllName || props.org.name
            list.push(props.org)
        }
        state.orgList = list;
    })
})
</script>

<style lang="scss" scoped>
.ChooseUserOne {
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    align-items: center;

    .user-label {
        padding: 0 10px 0 20px;
        font-size: 14px;
    }

}
</style>
